package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by WF on 2020/7/23 15:44
 */
@RestController
@RequestMapping("spit")
public class SpitController {
    @Autowired
    private SpitService spitService;
    @Autowired
    private RedisTemplate redisTemplate;
    //1.查询所有吐槽列表
    @GetMapping
    public Result findAll(){
        //1.1)查询所有吐槽列表
        List<Spit> spitList = spitService.findAll();
        //1.2)返回
        return new Result(true, StatusCode.OK,"查询吐槽列表成功！",spitList);
    }
    //2.添加吐槽
    @PostMapping
    public Result add(@RequestBody Spit spit){
        //2.1)添加吐槽
        spitService.add(spit);
        //3.2)返回
        return new Result(true, StatusCode.OK,"添加吐槽成功！");
    }
    //3.根据id查询吐槽
    @GetMapping("{spitId}")
    public Result findById(@PathVariable String spitId){
        //3.1)查询单个
        Spit spit = spitService.findById(spitId);
        //3.2)返回
        return new Result(true, StatusCode.OK,"查询吐槽成功！",spit);
    }
    //4.修改吐槽
    @PutMapping("{spitId}")
    public Result update(@PathVariable String spitId,@RequestBody Spit spit){
        //4.1)将吐槽id与吐槽对象关联
        spit.set_id(spitId);
        //4.2)修改吐槽
        spitService.update(spit);
        //4.3)提示返回
        return new Result(true,StatusCode.OK,"修改吐槽成功！");
    }
    //5.删除吐槽
    @DeleteMapping("{spitId}")
    public Result delete(@PathVariable String spitId){
        //5.1)根据id删除吐槽
        spitService.deleteById(spitId);
        //4.3)提示返回
        return new Result(true,StatusCode.OK,"删除吐槽成功！");
    }
    //6.根据上级id查询吐槽列表
    @GetMapping("comment/{parentid}/{page}/{size}")
    public Result findByPage(@PathVariable String parentid,@PathVariable int page,@PathVariable int size){
        //6.1)查询上级id的吐槽列表
        PageResult<Spit> pageResult = spitService.findByPage(parentid,page,size);
        //6.2)返回
        return new Result(true,StatusCode.OK,"查询父id列表成功！",pageResult);
    }
    //7.吐槽点赞
    @PutMapping("thumbup/{spitId}")
    public Result thumbup(@PathVariable String spitId){
        //如何避免重复点赞?在redis中设置一个标志即可
        Object flag = redisTemplate.opsForValue().get("thumbup_aa" + spitId);
        //如果这个flag没有值，就证明没有点赞过
        if(flag == null){
            //7.1)开始吐槽点赞
            spitService.thumbup(spitId);
            //7.2)将标志位放到redis中
            System.out.println("将标志位放到redis中了。。。。");
            redisTemplate.opsForValue().set("thumbup_aa" + spitId,"test");
            //7.2)返回
            return new Result(true,StatusCode.OK,"点赞成功！");
        }
        return new Result(false,StatusCode.REPERROR,"不能重复点赞！");
    }
}
